package com.demo.config;

import com.demo.log.Logger;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * @author wangfengchen
 */
@Component
public class HttpConfig {
  private static final Logger logger = Logger.get(HttpConfig.class);
  private static OkHttpClient okHttpClient;
  private long connectTimeout = 2000;
  private long readTimeout = 2000;
  private long writeTimeout = 2000;

  private int maxIdleConnections = 20;

  private long keepAliveDuration = 50;


  public OkHttpClient getOkHttpClient() {
    return okHttpClient;
  }


  @PostConstruct
  private void init() {
    OkHttpClient.Builder okHttpClientBuilder = getBuilder();
    okHttpClient = okHttpClientBuilder.build();
    logger.info("okHttpClient初始化成功");
  }

  @PreDestroy
  private void destroy() {
    destroy(okHttpClient);
    logger.info("okHttpClient关闭成功");
  }

  private OkHttpClient.Builder getBuilder() {
    return new OkHttpClient.Builder()
        .connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS))
        .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
        .connectTimeout(writeTimeout, TimeUnit.MILLISECONDS)
        .writeTimeout(connectTimeout, TimeUnit.MILLISECONDS)
        ;
  }

  private void destroy(OkHttpClient okHttpClient) {
    ExecutorService threadPool = okHttpClient.dispatcher().executorService();
    threadPool.shutdown();
    try {
      if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
        threadPool.shutdownNow();
      }
    } catch (InterruptedException e) {
      threadPool.shutdownNow();
      Thread.currentThread().interrupt();
    }
    okHttpClient.connectionPool().evictAll();
  }

  public static Request getGetRequest(String url) {
    return new Request.Builder()
        .url(url)
        .get()
        .addHeader("accept", "application/json")
        .build();
  }

  public static Request getPostRequest(String url, RequestBody body) {
    return new Request.Builder()
        .url(url)
        .post(body)
        .addHeader("accept", "application/json")
        .addHeader("content-type", "application/json")
        .build();
  }

  public static Request getDeleteRequest(String url) {
    return new Request.Builder()
        .url(url)
        .delete()
        .addHeader("accept", "application/json")
        .build();
  }


}
